<template>
    <div class="carousel-management">
        <h4>轮播图管理</h4>

        <!-- 筛选区域 -->
        <el-card class="filter-card">
            <div class="filter-container">
                <div class="filter-item">
                    <span class="filter-label">轮播图标题：</span>
                    <el-input v-model="filterForm.Title" style="width: 200px" placeholder="输入标题或关键字" clearable />
                    <span class="filter-label">上传时间：</span>
                    <el-date-picker v-model="filterForm.dateRange" type="daterange" range-separator="--"
                        start-placeholder="开始时间" end-placeholder="结束时间" :size="size" @change="handleDateChange" />
                    <span class="filter-label">状态：</span>
                    <el-select v-model="filterForm.Status" placeholder="请选择状态" clearable style="width: 120px">
                        <el-option label="上架" value="true" />
                        <el-option label="下架" value="false" />
                    </el-select>
                </div>
                <br>
                <el-button type="primary" @click="handleFilter">筛选</el-button>
                <el-button @click="resetFilter">重置</el-button>
            </div>
        </el-card>

        <!-- 轮播图列表 -->
        <el-card class="list-card">
            <div class="list-header">
                <h5>轮播图列表</h5>
                <div class="list-actions">
                    <el-button type="success" @click="handleAdd">新增轮播图</el-button>
                    <el-button type="danger" @click="handleBatchDelete"
                        :disabled="selectedRows.length === 0">批量删除</el-button>
                </div>
            </div>

            <el-table ref="tableRef" :data="tableData" border style="width: 100%"
                @selection-change="handleSelectionChange" v-loading="loading">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="carouelChartTitle" label="轮播图标题" width="180" />
                <el-table-column label="缩略图" width="180">
                    <template #default="scope">
                        <el-image :src="scope.row.carouelChartImages" :preview-src-list="[scope.row.carouelChartImages]"
                            fit="cover" style="width: 80px; height: 45px; border-radius: 4px;" />
                    </template>
                </el-table-column>
                <el-table-column prop="ststus" label="状态" width="100">
                    <template #default="scope">
                        <el-tag :type="scope.row.ststus === true ? 'success' : 'info'">
                            {{ scope.row.ststus === true ? '上架' : '下架' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createdBy" label="上传人">
                    <template #default="scope">
                        {{ scope.row.createdBy == 0 ? 'admin' : '普通用户' }}
                    </template>
                </el-table-column>
                <el-table-column prop="createdTime" label="上传时间">
                    <template #default="scope">
                        {{ moment(scope.row.createdTime).format('yyyy-MM-DD HH:mm') }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <div class="pagination-left">
                    <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
                    <span class="pagination-info">共{{ page.pageCount }}页/{{ page.totalCount }}条数据</span>
                </div>
                <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
                    :page-sizes="[4, 8, 10, 20, 100]" :total="page.totalCount"
                    layout="total, sizes, prev, pager, next, jumper" prev-text="上一页" next-text="下一页"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增轮播图' : '编辑轮播图'" width="600px"
            @close="resetForm">
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" label-position="right">
                <el-form-item label="轮播图标题" prop="carouelChartTitle">
                    <el-input v-model="formData.carouelChartTitle" placeholder="请输入轮播图标题" />
                </el-form-item>

                <el-form-item label="轮播图" prop="carouelChartImages">
                    <el-upload class="image-upload" :action="uploadUrl" :headers="uploadHeaders" :show-file-list="false"
                        :on-success="handleUploadSuccess" :on-error="handleUploadError" :before-upload="beforeUpload"
                        :on-progress="handleUploadProgress" :data="uploadData" name="imageFile" accept="image/*"
                        :multiple="false" drag v-loading="uploadLoading">
                        <div class="upload-area" :class="{ 'upload-success': uploadSuccess }">
                            <el-image v-if="formData.carouelChartImages" :src="formData.carouelChartImages" fit="cover"
                                style="width: 100%; height: 100%; border-radius: 4px;"
                                :preview-src-list="[formData.carouelChartImages]" preview-teleported />
                            <div v-else class="upload-placeholder">
                                <el-icon>
                                    <Plus />
                                </el-icon>
                                <div class="upload-text">点击上传图片</div>
                            </div>
                            <!-- 上传成功后的覆盖层 -->
                            <div v-if="formData.carouelChartImages" class="upload-overlay">
                                <div class="upload-success-icon">
                                    <el-icon color="#67c23a" size="24">
                                        <Check />
                                    </el-icon>
                                </div>
                            </div>
                            <!-- 上传成功提示 -->
                            <div v-if="uploadSuccess" class="upload-success-message">
                                <el-icon color="#67c23a" size="20">
                                    <Check />
                                </el-icon>
                                <span>上传成功</span>
                            </div>
                        </div>
                    </el-upload>
                    <div class="upload-tip">建议尺寸375*211，不要超过1M</div>
                    <!-- 图片信息显示 -->
                    <div v-if="formData.carouelChartImages" class="image-info">
                        <el-tag size="small" type="success">已上传</el-tag>
                        <!-- <span class="image-url">{{ formData.carouelChartImages }}</span> -->
                        <el-button size="small" type="primary" @click="reuploadImage">重新上传</el-button>
                    </div>
                    <!-- 上传历史 -->
                    <div v-if="uploadHistory.length > 0" class="upload-history">
                        <div class="history-title">最近上传的图片：</div>
                        <div class="history-list">
                            <div v-for="(url, index) in uploadHistory" :key="index" class="history-item">
                                <el-image :src="url" style="width: 60px; height: 34px; border-radius: 4px;"
                                    fit="cover" />
                                <!-- <span class="history-url">{{ url }}</span> -->
                                <el-button size="small" @click="selectHistoryImage(url)">选择</el-button>
                            </div>
                        </div>
                    </div>
                </el-form-item>

                <el-form-item label="轮播图状态" prop="ststus">
                    <el-switch v-model="formData.ststus" :active-value="true" :inactive-value="false" active-text="上架"
                        inactive-text="下架" />
                </el-form-item>

                <el-form-item label="轮播图链接地址" prop="carouelChartUrl">
                    <el-input v-model="formData.carouelChartUrl" placeholder="请输入链接地址" />
                </el-form-item>

                <el-form-item label="排序" prop="orderby">
                    <el-input-number v-model="formData.orderby" :min="1" :max="999" placeholder="请输入排序数字" />
                    <span class="sort-tip">填写数字，数字越大越靠前</span>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">提交</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Check } from '@element-plus/icons-vue'
import { readB, writeB } from '@/api/http'
import moment from 'moment'

// 定义轮播图数据类型
interface CarouselItem {
    id: string
    carouelChartTitle: string
    carouelChartImages: string
    ststus: boolean
    carouelChartUrl: string
    orderby: number
    createdBy: number
    createdTime: string
}

// 响应式数据
const tableData = ref<CarouselItem[]>([])
const loading = ref(false)
const submitLoading = ref(false)
const uploadLoading = ref(false)
const uploadSuccess = ref(false)
const uploadHistory = ref<string[]>([])
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const tableRef = ref()
const selectedRows = ref<CarouselItem[]>([])
const selectAll = ref(false)

// 筛选表单
const filterForm = reactive({
    Title: '',
    dateRange: [],
    Status: '',
    startTime: '',
    endTime: ''
})

// 分页参数
const page = reactive({
    PageIndex: 1,
    PageSize: 4,
    totalCount: 0,
    pageCount: 0,
})

// 表单数据
const formData = reactive({
    id: '',
    carouelChartTitle: "",
    carouelChartImages: "",
    ststus: true,
    carouelChartUrl: "",
    orderby: 0
})

// 表单验证规则
const formRules: FormRules = {
    carouelChartTitle: [
        { required: true, message: '请输入轮播图标题', trigger: 'blur' }
    ],
    carouelChartImages: [
        { required: true, message: '请上传轮播图', trigger: 'change' }
    ],
    carouelChartUrl: [
        { required: true, message: '请输入链接地址', trigger: 'blur' }
    ],
    orderby: [
        { required: true, message: '请输入排序数字', trigger: 'blur' }
    ]
}

// 上传相关
const uploadUrl = 'http://47.95.68.41:4560/api/Carousel/UploadCarouselImage/upload-image?bucketName=image&prefix=carousel' // 使用writeB的baseURL
const uploadHeaders = {
    // 根据实际需要添加认证头
    'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
}

// 上传参数
const uploadData = {
    bucketName: 'image',
    prefix: 'carousel'
}

// 组件大小
const size = ref('default')

// 获取轮播图列表
const getCarouselList = async () => {
    loading.value = true
    try {
        const res = await readB.get("/api/Carousel/GetCarouselList/list", {
            params: {
                startTime: filterForm.startTime,
                endTime: filterForm.endTime,
                Title: filterForm.Title,
                Status: filterForm.Status,
                PageIndex: page.PageIndex,
                PageSize: page.PageSize,
            }
        })

        if (res.data.code === 200) {
            tableData.value = res.data.data
            page.totalCount = res.data.totalCount
            page.pageCount = res.data.pageCount
            // 清除选择状态
            selectedRows.value = []
            selectAll.value = false
        } else {
            ElMessage.error(res.data.message || '获取数据失败')
        }
    } catch (error) {
        ElMessage.error('获取数据失败')
        console.error(error)
    } finally {
        loading.value = false
    }
}

// 筛选处理
const handleFilter = () => {
    page.PageIndex = 1
    getCarouselList()
}

// 重置筛选
const resetFilter = () => {
    Object.assign(filterForm, {
        title: '',
        dateRange: [],
        status: '',
        startTime: '',
        endTime: ''
    })
    page.PageIndex = 1
    getCarouselList()
}

// 日期变化处理
const handleDateChange = (dates: any) => {
    if (dates && dates.length === 2) {
        filterForm.startTime = dates[0]
        filterForm.endTime = dates[1]
    } else {
        filterForm.startTime = ''
        filterForm.endTime = ''
    }
}

// 选择处理
const handleSelectionChange = (rows: CarouselItem[]) => {
    selectedRows.value = rows
    selectAll.value = rows.length === tableData.value.length && tableData.value.length > 0
}

// 全选处理
const handleSelectAll = (checked: boolean) => {
    if (!tableRef.value) return

    if (checked) {
        // 选中所有行
        tableData.value.forEach((row) => {
            tableRef.value.toggleRowSelection(row, true)
        })
    } else {
        // 取消选中所有行
        tableRef.value.clearSelection()
    }
}

// 分页处理
const handleSizeChange = (size: number) => {
    page.PageSize = size
    page.PageIndex = 1
    getCarouselList()
}

const handleCurrentChange = (current: number) => {
    page.PageIndex = current
    getCarouselList()
}

// 新增轮播图
const handleAdd = () => {
    dialogType.value = 'add'
    dialogVisible.value = true
    resetForm()
}

// 编辑轮播图
const handleEdit = (row: any) => {
    dialogType.value = 'edit'
    dialogVisible.value = true
    Object.assign(formData, {
        id: row.id,
        carouelChartTitle: row.carouelChartTitle,
        carouelChartImages: row.carouelChartImages,
        ststus: row.ststus,
        carouelChartUrl: row.carouelChartUrl,
        orderby: row.orderby
    })
}

// 删除轮播图
const handleDelete = async (row: any) => {
    // console.log("res.data=>", row.id)


    try {
        await ElMessageBox.confirm('确定要删除这个轮播图吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        const res = await writeB.post(`/api/Carousel/BatchDeleteCarousel/batch-delete`, { ids: [row.id] })

        if (res.data.code === 200) {
            ElMessage.success('删除成功')
            getCarouselList()
        } else {
            ElMessage.error(res.data.message || '删除失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败')
        }
    }
}

// 批量删除
const handleBatchDelete = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的轮播图')
        return
    }

    try {
        await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个轮播图吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        const ids = selectedRows.value.map((row: CarouselItem) => row.id)
        const res = await writeB.post('/api/Carousel/BatchDeleteCarousel/batch-delete', { ids: ids })

        if (res.data.code === 200) {
            ElMessage.success('批量删除成功')
            selectedRows.value = []
            getCarouselList()
        } else {
            ElMessage.error(res.data.message || '批量删除失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('批量删除失败')
        }
    }
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        submitLoading.value = true

        const url = dialogType.value === 'add'
            ? '/api/Carousel/AddCarousel/add'
            : '/api/Carousel/UpdateCarousel/update'

        // 确保数据格式正确
        const submitData = {
            ...formData,
            ststus: formData.ststus
        }

        const res = await writeB.post(url, submitData)

        if (res.data.code === 200) {
            ElMessage.success(dialogType.value === 'add' ? '新增成功' : '更新成功')
            dialogVisible.value = false
            getCarouselList()
        } else {
            ElMessage.error(res.data.message || '操作失败')
        }
    } catch (error) {
        console.error(error)
    } finally {
        submitLoading.value = false
    }
}

// 重置表单
const resetForm = () => {
    if (formRef.value) {
        formRef.value.resetFields()
    }
    Object.assign(formData, {
        id: '',
        carouelChartTitle: '',
        carouelChartImages: '',
        ststus: true,
        carouelChartUrl: '',
        orderby: 0
    })
}

// 上传相关方法
const beforeUpload = (file: File) => {
    const isImage = file.type.startsWith('image/')
    const isLt1M = file.size / 1024 / 1024 < 1

    if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return false
    }
    if (!isLt1M) {
        ElMessage.error('图片大小不能超过 1MB!')
        return false
    }

    // 检查图片尺寸
    return new Promise((resolve) => {
        const reader = new FileReader()
        reader.onload = (e) => {
            const img = new Image()
            img.onload = () => {
                const width = img.width
                const height = img.height
                const recommendedWidth = 375
                const recommendedHeight = 211

                if (width !== recommendedWidth || height !== recommendedHeight) {
                    ElMessage.warning(`建议图片尺寸为 ${recommendedWidth}x${recommendedHeight}，当前尺寸为 ${width}x${height}`)
                }

                uploadLoading.value = true
                resolve(true)
            }
            img.src = e.target?.result as string
        }
        reader.readAsDataURL(file)
    })
}

const handleUploadSuccess = (response: any) => {
    console.log("response", response)
    uploadLoading.value = false

    if (response.code === 200) {
        // 根据API响应格式处理图片URL
        const imageUrl = response.data?.url || response.data || response
        formData.carouelChartImages = imageUrl
        formData.carouelChartUrl = imageUrl
        // 添加到上传历史
        uploadHistory.value.unshift(imageUrl)
        if (uploadHistory.value.length > 5) {
            uploadHistory.value.pop()
        }

        // 显示上传成功状态
        uploadSuccess.value = true
        setTimeout(() => {
            uploadSuccess.value = false
        }, 2000)

        // 显示上传成功的图片
        showUploadedImage(imageUrl)

        ElMessage.success('上传成功')
    } else {
        ElMessage.error(response.message || '上传失败')
    }
}

const handleUploadError = (error: any, file: any) => {
    console.error('Upload error:', error)
    console.error('Upload file:', file)
    uploadLoading.value = false
    ElMessage.error('上传失败，请检查网络连接或文件格式')
}

const handleUploadProgress = (event: any, file: any) => {
    console.log('Upload progress:', event.percent)
}

// 显示上传成功的图片
const showUploadedImage = (imageUrl: string) => {
    // 创建一个图片预览对话框
    ElMessageBox.alert(
        `<div style="text-align: center;">
            <img src="${imageUrl}" style="max-width: 100%; max-height: 400px; border-radius: 8px;" />
            <p style="margin-top: 10px; color: #67c23a;">图片上传成功！</p>
            <div style="margin-top: 10px; font-size: 12px; color: #909399;">
                <p>上传时间: ${new Date().toLocaleString()}</p>
            </div>
        </div>`,
        '上传成功',
        {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '确定',
            customClass: 'upload-success-dialog'
        }
    )
}

// 重新上传图片
const reuploadImage = () => {
    formData.carouelChartImages = ''
    ElMessage.info('请重新选择图片上传')
}

// 选择历史图片
const selectHistoryImage = (url: string) => {
    formData.carouelChartImages = url
    ElMessage.success('已选择历史图片')
}

// 生命周期
onMounted(() => {
    getCarouselList()
})
</script>

<style scoped>
.carousel-management {
    padding: 20px;
}

.filter-card {
    margin-bottom: 20px;
}

.filter-container {
    display: flex;
    align-items: center;
    gap: 20px;
    flex-wrap: wrap;
}

.filter-item {
    display: flex;
    align-items: center;
    gap: 8px;
}

.filter-label {
    white-space: nowrap;
    font-weight: 500;
}

.list-card {
    margin-top: 20px;
}

.list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.list-header h5 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
}

.list-actions {
    display: flex;
    gap: 10px;
}

.pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
}

.pagination-left {
    display: flex;
    align-items: center;
    gap: 20px;
}

.pagination-info {
    color: #606266;
    font-size: 14px;
}

.image-upload {
    width: 100%;
}

.upload-area {
    width: 375px;
    height: 211px;
    border: 2px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
    display: flex;
    align-items: center;
    justify-content: center;
}

.upload-area:hover {
    border-color: #409eff;
}

.upload-area.is-dragover {
    border-color: #409eff;
    background-color: #f0f9ff;
}

.upload-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    opacity: 0;
    transition: opacity 0.3s;
}

.upload-area:hover .upload-overlay {
    opacity: 1;
}

.upload-success-icon {
    background: rgba(255, 255, 255, 0.9);
    border-radius: 50%;
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.upload-success {
    border-color: #67c23a !important;
    box-shadow: 0 0 10px rgba(103, 194, 58, 0.3);
}

.upload-success-message {
    position: absolute;
    top: 10px;
    right: 10px;
    background: rgba(103, 194, 58, 0.9);
    color: white;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    display: flex;
    align-items: center;
    gap: 4px;
    animation: fadeInOut 2s ease-in-out;
}

@keyframes fadeInOut {
    0% {
        opacity: 0;
        transform: translateY(-10px);
    }

    20% {
        opacity: 1;
        transform: translateY(0);
    }

    80% {
        opacity: 1;
        transform: translateY(0);
    }

    100% {
        opacity: 0;
        transform: translateY(-10px);
    }
}

.image-info {
    margin-top: 8px;
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px;
    background: #f5f7fa;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
}

.image-url {
    font-size: 12px;
    color: #606266;
    word-break: break-all;
    flex: 1;
}

.upload-history {
    margin-top: 12px;
    padding: 12px;
    background: #f8f9fa;
    border-radius: 6px;
    border: 1px solid #e9ecef;
}

.history-title {
    font-size: 14px;
    font-weight: 500;
    color: #495057;
    margin-bottom: 8px;
}

.history-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.history-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px;
    background: white;
    border-radius: 4px;
    border: 1px solid #dee2e6;
}

.history-url {
    font-size: 12px;
    color: #6c757d;
    flex: 1;
    word-break: break-all;
}

.upload-placeholder {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
    color: #8c939d;
}

.upload-placeholder .el-icon {
    font-size: 28px;
    margin-bottom: 8px;
}

.upload-text {
    font-size: 14px;
}

.upload-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 8px;
}

.sort-tip {
    font-size: 12px;
    color: #909399;
    margin-left: 8px;
}

.dialog-footer {
    text-align: right;
}
</style>